package com.xiangxiao.rpan.storage.threadpool;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/12/25 17:58
 */
@Configuration
@EnableAsync
public class AsyncTaskWithThreadPool {

  private static final Logger logger = LoggerFactory.getLogger(AsyncTaskWithThreadPool.class.getName());
  private static final int availableProcessors =  Runtime.getRuntime().availableProcessors();

  @Bean("asyncTaskExecutor")
  public Executor asyncServiceExecutor() {
    logger.info("start asyncServiceExecutor");
    ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
    //配置核心线程数
    executor.setCorePoolSize(100);
    //配置最大线程数
    executor.setMaxPoolSize(200);
    //配置队列大小
    executor.setQueueCapacity(Integer.MAX_VALUE);
    //配置线程池中的线程的名称前缀
    executor.setThreadNamePrefix("file-service-");
    //配置线程允许的空闲时间
    executor.setKeepAliveSeconds(60);
    //拒绝策略
    executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    //执行初始化
    executor.initialize();
    return executor;
  }
}
